<template>
  <div class="base">
    <div class="name text-ellipsis">{{ from }}</div>
    <div class="date">{{ date }}</div>
  </div>
</template>

<script>
import { getFullDate } from '../../utils/date';
import { mapState } from 'vuex';

export default {
  name: 'MessageHeader',
  props: {
    message: {
      type: Object,
      required: true
    }
  },
  computed: {
    ...mapState({
      currentConversation: state => state.conversation.currentConversation,
      currentUserProfile: state => state.user.currentUserProfile,
      currentMemberList: state => state.group.currentMemberList
    }),
    date() {
      return getFullDate(new Date(this.message.time * 1000));
    },
    from() {
      if(this.message.conversationType === this.TIM.TYPES.CONV_SYSTEM){
        return this.message.type === this.TIM.TYPES.MSG_GRP_SYS_NOTICE ? '群系统通知' : '系统通知';
      }
      else if(this.message.conversationType === this.TIM.TYPES.CONV_C2C){
        if (this.isMine) {
          return this.currentUserProfile.nick || this.currentUserProfile.userID;
        }
        return this.currentConversation.userProfile.nick || this.currentConversation.userProfile.userID;
      }
      else if(this.message.conversationType === this.TIM.TYPES.CONV_GROUP){
        const fromProfile = this.currentMemberList.find( profile => {
          return profile.userID === this.message.from;
        });
        // 若fromProfile不为空，则返回群昵称>个人昵称>用户ID
        // 该判断的场景为：切换会话后，上一个会话的消息仍会触发该方法，不加判断会报错
        if(fromProfile){
          return fromProfile.nameCard || fromProfile.nick || fromProfile.userID;
        }
      }
      return  this.message.nick || this.message.from;
    },
    isMine() {
      return this.message.flow === 'out';
    }
  }
}
</script>

<style scoped>
.base {
  display: flex;
  padding: 5px;
  font-size: 12px;
}

.name {
  padding: 0 4px;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
